﻿namespace USElections.Tiles
{
    using System.ComponentModel;
    using System.Linq;
    using System.ServiceModel.Syndication;
    using System.Windows.Controls;
    using USElections.NewsFeeds.Model;

    public partial class NewsFeedsBackTile : UserControl, INotifyPropertyChanged
    {
        private RssFeeds rssFeeds = Data.Instance.RssFeeds;
        private int counter = 0;
        private string feedname;
        private string title;

        public NewsFeedsBackTile()
        {
            InitializeComponent();

            this.DataContext = this;

            this.Loaded += this.NewsFeedsBackTile_Loaded;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public string FeedName
        {
            get
            {
                return this.feedname;
            }
            internal set
            {
                this.feedname = value;
                this.NotifyPropertyChanged("FeedName");
            }
        }

        public string Title
        {
            get
            {
                return this.title;
            }
            internal set
            {
                this.title = value;
                this.NotifyPropertyChanged("Title");

            }
        }

        private void NewsFeedsBackTile_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            int count = this.rssFeeds.Count;

            if (count != 0)
            {
                RssFeedModel feed = this.rssFeeds[counter];

                var item = feed.OriginalItems.FirstOrDefault<SyndicationItem>();

                if (item != null && item.Title != null)
                {
                    this.FeedName = feed.Name;
                    this.Title = item.Title.Text;
                }

                if (counter == (count - 1))
                {
                    counter = 0;
                }
                else
                {
                    counter++;
                }
            }
        }

        #region Private methods
        private void NotifyPropertyChanged(string name)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
        #endregion
    }
}